<script setup name="TreeSelectMany">
import {getCurrentInstance, nextTick, reactive} from "vue";

const {proxy} = getCurrentInstance();
const treeSelectManyRef = ref(null);
const props = defineProps({
  // 输入的id，用于 3、4样式的数据展示
  // 每个对象的主键类型可能不一样，大部分的都是Number类型的。
  checkedKeys: {
    type: Array,
    default: null,
  },
  // 因为有可能在表格中供用户选择，如果每行数据都刷新一次，数据库消耗太大了。
  // 在页面外面获取一次，每个行的每个对象都能使用了，直接赋值给下拉列表
  treeList: {
    type: Array,
    default: null,
  },
  //  关键字名称
  id: {
    type: String,
    default: "id"
  },
  // 树节点列名
  name: {
    type: String,
    default: "name"
  },
  // 树节点列名
  children: {
    type: String,
    default: "children"
  }
});

let pd = reactive({
  treeList: [],
  checkedKeys: [],
  expand: false,
  nodeAll: false,
  checkStrictly: false,
  queryParams: {
    id: null,
    parentId: null
  }
});

defineExpose({
  initTreeSelectMany,getAllCheckedKeys
});

/** 所有节点数据 */
function getAllCheckedKeys() {
  // 目前被选中的节点
  let checkedKeys = treeSelectManyRef.value.getCheckedKeys();
  // 半选中的节点
  let halfCheckedKeys = treeSelectManyRef.value.getHalfCheckedKeys();
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
}

watch(() => props.treeList, val => {
  initTreeSelectMany();
}, {deep: true, immediate: true});

watch(() => props.checkedKeys, val => {
  if (!pd.treeList) {
    return;
  }
  if (props.checkedKeys) {
    return;
  }

  props.checkedKeys.forEach((v) => {
      treeSelectManyRef.value.setChecked(v, true, false);
  });
}, {deep: true, immediate: true});

// 初始化3、4样式的展示
function initTreeSelectMany() {
  if (pd.treeList.length > 0) {
    return;
  }
  if (props.treeList) {
    pd.treeList = props.treeList;
  }
}

/** 树权限（展开/折叠）*/
function handleCheckedTreeExpand(value) {
  let treeList = pd.treeList.value;
  for (let i = 0; i < treeList.length; i++) {
    treeSelectManyRef.value.store.nodesMap[treeList[i].id].expanded = value;
  }
}

/** 树权限（全选/全不选） */
function handleCheckedTreeNodeAll(value) {
  treeSelectManyRef.value.setCheckedNodes(value ? pd.treeList.value : []);
}

/** 树权限（父子联动） */
function handleCheckedTreeConnect(value) {
  pd.checkStrictly = value ? true : false;
}

</script>

<template>

  <el-checkbox v-model="pd.expand" @change="handleCheckedTreeExpand">展开/折叠</el-checkbox>
  <el-checkbox v-model="pd.nodeAll" @change="handleCheckedTreeNodeAll">全选/全不选</el-checkbox>
  <el-checkbox v-model="pd.checkStrictly" @change="handleCheckedTreeConnect">父子联动</el-checkbox>
  <el-tree class="tree-border" :data="pd.treeList" show-checkbox ref="treeSelectManyRef" :node-key="props.id"
           :check-strictly="!pd.checkStrictly" empty-text="加载中，请稍候"
           :props="{ label: props.name, children: props.children }"></el-tree>
</template>

<style scoped>

</style>